<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <!-- :file-list="ruleForm.image" -->
    <div style="margin-left: 10px">房型图片</div>
    <el-upload
      v-model:file-list="fileList"
      list-type="picture-card"
      :limit="1"
      style="margin-bottom: 5px"
      :auto-upload="false"
      :multiple="false"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible" style="width: 550px; text-align: center">
      <img style="width: 450px" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <el-form-item v-if="actionType === 'update'" label="房型ID" prop="">
      <el-input v-model="ruleForm.id" disabled />
    </el-form-item>
    <el-form-item label="等级" prop="level">
      <el-select v-model="ruleForm.level" placeholder="请选择等级">
        <el-option
          v-for="item in levelOptions"
          :key="item.id"
          :label="item.level"
          :value="item.level"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="类型" prop="type">
      <el-select v-model="ruleForm.type" placeholder="请选择类型">
        <el-option
          v-for="item in typeOptions"
          :key="item.type"
          :label="item.type"
          :value="item.type"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="房型名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>

    <el-form-item label="床位数" prop="beds">
      <el-input v-model="ruleForm.beds" />
    </el-form-item>
    <el-form-item label="房费" prop="basicPrice">
      <el-input v-model="ruleForm.basicPrice" />
    </el-form-item>
    <el-form-item label="押金" prop="deposit">
      <el-input v-model="ruleForm.deposit" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button v-if="actionType === 'add'" type="info" @click="reset()"
        >重置</el-button
      >
      <el-button @click="close">关 闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import {
  ElMessage,
  UploadFile,
  UploadRawFile,
  type ComponentSize,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { RoomtypesForm } from "@/api/roomtypes";
import {
  getRoomTypeById,
  addRoomTypes,
  updateRoomTypes,
  listAllRoomTypes,
  getRoomTypeslevels,
  imgadd
} from "@/api/roomtypes";
import { RoomTypesDTO } from "@/api/rooms";

onMounted(() => {
  getlevels();
  getRoomTypesOptions();
});
onMounted(() => {
  getlevels();
  getRoomTypesOptions();
});
/** ------------------组件通信-接收数据-------------------- */
const currentImageUrl = ref<string>();
const emit = defineEmits(["close"]);
const props = defineProps({
  roomTypesId: {
    type: Number,
    default: null
  },
  action: {
    type: String,
    default: null
  },
  ruleform: {
    type: Object as PropType<RoomtypesForm>,
    default: null
  },
  dialogOpen: {
    type: Boolean,
    default: null
  }
});
const ruleForm = ref<RoomtypesForm>({
  id: undefined,
  name: undefined,
  beds: undefined,
  basicPrice: undefined,
  level: undefined,
  type: undefined,
  deposit: undefined
  // image: []
});
const actionType = ref<string>();
watch(
  [() => props.roomTypesId, () => props.action],
  ([newRoomTypesId, newAction], [oldRoomTypesId, oldAction]) => {
    ruleForm.value = {
      ...props.ruleform
    };
    if (newRoomTypesId !== null) {
      initData(newRoomTypesId);
    }
    actionType.value = newAction;
  },
  { deep: true, immediate: true }
);
watch(
  () => props.dialogOpen,
  (newDialogOpen, oldDialogOpen) => {
    if (newDialogOpen === false) {
      close();
    }
  },
  { deep: true, immediate: true }
);

/** ------------------加载初始化数据-------------------- */
const dialogImageUrl = ref("");
function initData(_categoryId: number) {
  setTimeout(() => {
    // actionType.value = props.action;
    if (props.roomTypesId !== null) {
      getRoomTypeById(_categoryId).then(response => {
        ruleForm.value = response.data;
        const url = response.data.image;
        if (url !== "") {
          const lastSlashIndex = url.lastIndexOf("/");
          const name = url.substring(lastSlashIndex + 1);
          if (fileList.value.length > 0) {
            fileList.value[0].url = url;
            fileList.value[0].name = name;
            fileList.value[0].status = "ready";
          } else {
            // 如果 fileList 为空，则添加一个新的 UploadFile 对象
            fileList.value.push({
              name,
              url,
              status: "ready",
              uid: undefined
            });
          }
        } else fileList.value = [];
      });
    } else fileList.value = [];
  }, 50);
}

/** ------------------表单数据-------------------- */
// 表单属性size
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const typeOptions = ref([
  {
    type: "单人间"
  },
  {
    type: "双人间"
  }
]);

const levelOptions = ref([]);
function getlevels() {
  getRoomTypeslevels().then(response => {
    levelOptions.value = response.data;
    console.log(1);
  });
}
const roomTypesOptions = ref<RoomTypesDTO[]>([]);
function getRoomTypesOptions() {
  listAllRoomTypes().then(response => {
    roomTypesOptions.value = response.data;
    console.log(2);
  });
}
//表单校验规则
const rules = reactive<FormRules<RoomtypesForm>>({
  // roomTypesName: [{ required: true, message: "类别名称不能为空", trigger: "change" }]
  type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  beds: [
    { required: true, message: "类型不能为空", trigger: "blur" },
    {
      pattern: /^[1-9]$/,
      message: "范围1-9",
      trigger: "blur"
    }
  ],
  basicPrice: [
    {
      pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
      required: true,
      message: "价格格式不正确, 参考20.50",
      trigger: "blur"
    }
  ],
  deposit: [
    {
      pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
      required: true,
      message: "押金格式不正确, 参考20.50",
      trigger: "blur"
    }
  ],
  level: [{ required: true, message: "等级不能为空", trigger: "blur" }]
});

/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(fileList.value);
  if (fileList.value.length === 0) {
    ElMessage.warning("请上传一张图片");
    return;
  }
  const file = new FormData();
  file.append("file", fileList.value[0].raw as File);
  await imgadd(file);
  console.log(file);
  console.log(fileList.value[0]);
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.roomTypesId !== null) {
        updateRoomTypes(ruleForm.value).then(response => {
          ElMessage.success("更新类别成功");
          close();
        });
      } else {
        addRoomTypes(ruleForm.value).then(response => {
          ElMessage.success("添加类别成功");
          close();
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/** 重置表单 */
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function reset() {
  resetForm(ruleFormRef.value);
  // actionType.value = undefined;
  ruleForm.value = {
    ...props.ruleform
  };
  fileList.value = [];
}

/** 关闭窗口 */
function close() {
  reset();
  emit("close");
}

const fileList = ref<UploadFile[]>([]);
const dialogVisible = ref(false);

// 处理超出限制时直接替换
const handleExceed = (files: File[]) => {
  fileList.value = [createUploadFile(files[0])];
  console.log(fileList.value);
};

// 统一创建上传文件对象parseInt( Date.now().toString(), 10);
const createUploadFile = (file: File): UploadFile => {
  // 创建符合 UploadRawFile 类型的对象
  const rawFile: UploadRawFile = Object.assign(file, {
    uid: parseInt(Date.now().toString(), 10)
  }) as UploadRawFile;

  return {
    uid: rawFile.uid,
    name: file.name,
    status: "ready",
    raw: rawFile,
    percentage: 0,
    size: file.size,
    url: URL.createObjectURL(file),
    response: undefined
  };
};

// 处理文件变化（常规上传时触发）
const handleChange = (filed: UploadFile) => {
  // 直接替换为最新文件
  fileList.value = [filed];
  // formData.append("file", file.raw);
};

// 图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url || URL.createObjectURL(file.raw as File);
  dialogVisible.value = true;
};

// 删除文件
const handleRemove = () => {
  fileList.value = [];
};
</script>
